package com.swy.controller;

import com.swy.model.SensitiveCheckResult;
import com.swy.service.SensitiveDetectorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/detector")
@RequiredArgsConstructor
public class DetectorController {

    private final SensitiveDetectorService detectorService;

    /**
     * 敏感词检测页面
     */
    @GetMapping({"", "/"})
    public String detectorPage() {
        return "detector";
    }

    /**
     * 上传文件并检测敏感词
     */
    @PostMapping("/check")
    @ResponseBody
    public List<SensitiveCheckResult> checkFiles(@RequestParam("files") MultipartFile[] files,
                                                 @RequestParam(value = "mode", defaultValue = "exact") String mode) {
        // 检查文件数量限制
        if (files.length > 100) {
            SensitiveCheckResult errorResult = new SensitiveCheckResult();
            errorResult.setFileName("N/A");
            errorResult.setErrorMessage("一次性最多只能检测 100 个文件。");
            return java.util.Collections.singletonList(errorResult);
        }
        // 异步检测文件
        List<CompletableFuture<SensitiveCheckResult>> futures = detectorService.detectFiles(files, mode);
        // 等待所有检测完成并收集结果
        List<SensitiveCheckResult> results = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
        return results;
    }
} 